package buaa.qel.rpc.common.util;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class ThreadPoolUtil {
    public static ThreadPoolExecutor makeServerThreadPool(final String serverName) {
        int corePoolSize = Math.max(Runtime.getRuntime().availableProcessors(),1 << 4);
        int maxPoolSize = corePoolSize << 1;
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                corePoolSize,
                maxPoolSize,
                30L,
                TimeUnit.SECONDS,
                new LinkedBlockingQueue<Runnable>(1000),
                new ThreadFactory() {
                    @Override
                    public Thread newThread(Runnable r) {
                        return new Thread(r, "buaa-qel-" + serverName + "-" + r.hashCode());
                    }
                },
                new ThreadPoolExecutor.AbortPolicy());
        return threadPoolExecutor;
    }

    public static ThreadPoolExecutor makeServerThreadPool(final String serverName,
                                                          int corePoolSize,
                                                          int maxPoolSize,
                                                          long keepAliveTime) {
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                corePoolSize,
                maxPoolSize,
                keepAliveTime,
                TimeUnit.SECONDS,
                new LinkedBlockingQueue<Runnable>(1000),
                new ThreadFactory() {
                    @Override
                    public Thread newThread(Runnable r) {
                        return new Thread(r, "buaa-qel-" + serverName + "-" + r.hashCode());
                    }
                },
                new ThreadPoolExecutor.AbortPolicy());
        return threadPoolExecutor;
    }
}
